import pandas as pd
from sqlalchemy import create_engine
from utils.mylib_db import *

# 数据库设置
############################################
# 创建数据库引擎
def PdConnDb():
    db = create_engine('mysql://%s:%s@%s:%s/%s' % (username, password, host, "3306", dbname))
    return db


def pd_select_db(table, where_condition=""):
    db = PdConnDb()

    if where_condition == "":
        sqlstr = "select * from %s" % table
    else:
        sqlstr = "select * from %s where %s" % (table, where_condition)

    print("select_db: %s" % sqlstr)
    # 从数据库中获取数据并转换为DataFrame格式
    df = pd.read_sql(sqlstr, db)
    db.dispose()

    return df


def pd_select_db_v2(table, select_str="*", where_condition=""):
    db = PdConnDb()

    if where_condition == "":
        sqlstr = "select %s from %s" % (select_str, table)
    else:
        sqlstr = "select %s from %s where %s" % (select_str, table, where_condition)

    print("select_db: %s" % sqlstr)
    # 从数据库中获取数据并转换为DataFrame格式
    df = pd.read_sql(sqlstr, db)
    db.dispose()

    return df
